import 'dart:io';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_syt/domain/epidemic/epidemic_health_list.dart';
import 'package:flutter_syt/generated/assets.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/root_widget.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/auto_image.dart';

loading(Future Function() load, {String text = "加载中..."}) async {
  if (text == '加载中...') {
    var ctx = navigatorKey.currentContext;
    if (ctx != null) {
      text = S.of(ctx).loading;
    }
  }
  return await EasyLoading.instance.flash(load, text: text);
}

customShowToast(String status) {
  EasyLoading.instance.loadingStyle = EasyLoadingStyle.dark;
  EasyLoading.showToast(status);
}

customShowError(String status) {
  EasyLoading.instance.loadingStyle = EasyLoadingStyle.dark;

  EasyLoading.showError(status);
}

customShowSuccess(String status) {
  EasyLoading.instance.loadingStyle = EasyLoadingStyle.dark;
  EasyLoading.showSuccess(status);
}

extension falshEx on EasyLoading {
  flash(Future Function() load, {String text = "加载中..."}) async {
    if (text == '加载中...') {
      var ctx = navigatorKey.currentContext;
      if (ctx != null) {
        text = S.of(ctx).loading;
      }
    }
    EasyLoading.instance.loadingStyle = EasyLoadingStyle.light;
    EasyLoading.instance.dismissOnTap = true;
    EasyLoading.show(
        status: text,
        maskType: EasyLoadingMaskType.black,
        indicator: const AutoImage(
          Assets.loading,
          width: 54,
          height: 54,
        ));
    try {
      dynamic res = await load();
      EasyLoading.dismiss();
      EasyLoading.instance.dismissOnTap = false;
      return res;
    } on DioError catch (e) {
      EasyLoading.dismiss();
      UtilsOther.showCustomShowError(e);
      // if (e.error is SocketException) {
      //   customShowToast(S().network_error);
      // } else {

      //   dynamic message = e.response?.data['message'];
      //   if (message != null && message != '') {
      //     customShowToast(message);
      //   } else {
      //     customShowToast(e.message);
      //   }
      // }
      rethrow;
    } catch (e) {
      if (e is String) {
        customShowToast(e);
      } else {
        EasyLoading.dismiss();
      }
      rethrow;
    }
  }

  toastError(Future Function() load) async {
    try {
      await load();
    } on DioError catch (e) {
      if (e.error is SocketException) {
        customShowToast(S().network_error);
      } else {
        customShowToast(e.message ?? '');
      }
      rethrow;
    } catch (e) {
      rethrow;
    }
  }
}
